package com.bjsxt;
/**线程同步案例    并行改为串行*/
/*银行取钱的案例*/
/*账户类*/
class Account{
    //账号
    private String accountNo;
    //账户的余额
    private double balance;
    public Account(){}

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

/*取款线程*/
//1,需要对那部分的代码进行同步
//2,让哪些线程具有同步的特点
class DrawThread extends Thread{
    //账户对象
    private Account account;
    //取款金额
    private double drawMoney;
    //创建构造方法，方便参数传递
    public DrawThread (String name,Account account,double drawMoney){
        super(name);//线程名称  利用线程名称区分人
        this.account = account;
        this.drawMoney = drawMoney;
    }
    //需要同步的代码
    /*取款线程*/
    @Override
    public void run() {
        //synchronized 不可以加在run()方法中，因为这是一个线程体
        //其它的方法可以
        //同一个账户时会出现并发现象，以账户为线程锁
        synchronized (this.account) {
            //判断当前账户余额是否大于或等于取款金额
            if (this.account.getBalance() >= this.drawMoney) {
                System.out.println(this.getName() + "取钱成功，吐出钞票" + this.drawMoney);
                try {  //让当前系统休眠，更改余额
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.account.setBalance(this.account.getBalance() - this.drawMoney);
                System.out.println("\t余额为：" + this.account.getBalance());
            } else {
                System.out.println(this.getName() + "取钱先败，余额不足");
            }
        }
    }
}
public class DrawMoneyThread {
    public static void main(String[] args) {
        //先实例化账户
        Account account = new Account("122",1000);
        //两个人取钱
        new DrawThread("老公",account,800).start();
        new DrawThread("老婆",account,800).start();
    }
}
